package com.ihighest.app.infox.adapter;

import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;

import com.ihighest.app.infox.R;
import com.ihighest.app.infox.activity.ApplyBeSpecialist;

import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;

/**
 * 申请专家界面选择省份适配器
 * 
 * @author lkx Created at 2015-11-17 下午5:23:41
 * @version 1.0
 */
public class ChooseProvincesAdapter extends BaseAdapter {
	private JSONArray array;
	private final Context context;
	private final LayoutInflater inflater;
	HashMap<Integer, Boolean> state = new HashMap<Integer, Boolean>();

	public ChooseProvincesAdapter(Context context) {
		this.context = context;
		this.inflater = LayoutInflater.from(context);
		this.array = new JSONArray();
	}

	public ChooseProvincesAdapter(Context context, JSONArray array) {
		this.context = context;
		this.inflater = LayoutInflater.from(context);
		this.array = array;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return array == null ? 0 : array.length();
	}

	@Override
	public Object getItem(int arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public long getItemId(int arg0) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public View getView(final int position, View contextView, ViewGroup parent) {
		ViewHolder holder;
		if (contextView == null) {
			holder = new ViewHolder();
			contextView = inflater.inflate(R.layout.infox_acivity_apply_specialis_choosedoalogt_item, null);

			holder.box = (CheckBox) contextView.findViewById(R.id.myProvinces);
			contextView.setTag(holder);
		} else {
			holder = (ViewHolder) contextView.getTag();
		}
		try {
			holder.box.setText(array.getJSONObject(position).getString("title"));
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		holder.box.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			private String areacode;

			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				try {
					areacode = array.getJSONObject(position).getString("areacode");
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (arg1) {

					ApplyBeSpecialist.mAddress.add(areacode);
					ApplyBeSpecialist.mGoodArea.add(arg0.getText().toString());
					state.put(position, arg1);
				} else {
					ApplyBeSpecialist.mAddress.remove(areacode);
					ApplyBeSpecialist.mGoodArea.remove(arg0.getText().toString());
					state.remove(position);
				}
			}
		});

		holder.box.setChecked(state.get(position) == null ? false : true);
		return contextView;
	}

	class ViewHolder {
		CheckBox box;
	}
}
